package gov.pbc.nn.kjgl.archive.view;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.bstek.bdf2.core.security.SecurityUtils;
import com.bstek.dorado.annotation.DataProvider;
import com.bstek.dorado.annotation.DataResolver;
import com.bstek.dorado.annotation.Expose;
import com.bstek.dorado.core.Configure;
import com.bstek.dorado.data.provider.Criteria;
import com.bstek.dorado.data.provider.Page;

import gov.pbc.nn.core.bdf.role.RoleMemberMaintain;
import gov.pbc.nn.core.bdf.service.DeptService;
import gov.pbc.nn.core.bdf.service.UserService;
import gov.pbc.nn.kjgl.archive.dao.ArchivesDao;
import gov.pbc.nn.kjgl.archive.dao.ArchivesInputDao;
import gov.pbc.nn.kjgl.entity.Archives;
import gov.pbc.nn.kjgl.entity.ArchivesContent;
import gov.pbc.nn.kjgl.entity.ArchivesMember;

@Component("archivesPR")
public class ArchivesPR {

	private static final String ROLE_DACX = "档案查询";
	private static final String ROLE_EJDAGLY = "二级档案管理员";
	private static final String ROLE_DALRY = "档案录入员";

	private static final String PATHURL = "e:/jatools/";
	// private static final String PATHURL2 = "e:/test/";

	@Autowired
	private ArchivesDao archivesDao;

	@Autowired
	private ArchivesInputDao archivesInputDao;

	@Autowired
	@Qualifier(DeptService.BEAN_ID)
	private DeptService deptService;

	@Autowired
	@Qualifier(UserService.BEAN_ID)
	private UserService userService;

	@Autowired
	private RoleMemberMaintain roleMemberMaintain;

	/**
	 * 获取档案
	 * 
	 * @return
	 */
	@DataProvider
	public List<Archives> getArchives() {
		return archivesDao.getArchives();

	}

	/**
	 * 获取子档案
	 * 
	 * @param parentId
	 * @return
	 */
	@DataProvider
	public List<Archives> getArchivesByParentId(String parentId) {
		return archivesDao.getArchivesByParentId(parentId);
	}

	/**
	 * 档案维护
	 * 
	 * @param archives
	 */
	@Transactional
	@DataResolver
	public void saveArchives(Collection<Archives> archives) {
		archivesDao.saveArchives(archives);
	}

	/**
	 * 判断名字是否重复
	 * 
	 * @param name
	 * @param type
	 * @return
	 */
	@Expose
	@Transactional
	public boolean checkName(String name, int type, String oneId) {
		return archivesDao.checkName(name, type, oneId);
	}

	/**
	 * 通过parentId获取子节点数
	 * 
	 * @param parentId
	 * @return
	 */
	@Expose
	@Transactional
	public int countChildren(String parentId) {
		return archivesDao.countChildren(parentId);
	}

	/**
	 * 添加档案权限关系
	 * 
	 * @param archivesId
	 * @param ids
	 * @param type
	 */
	@Transactional
	@Expose
	public void insert(String archivesId, Collection<String> ids, int type) {
		try {
			Collection<String> newid = new ArrayList<String>();
			String hql = "select count(*) from ArchivesMember where memberId=:id and archivesId=:archivesId and invalid=false and type=:type";
			for (String id : ids) {
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("id", id);
				map.put("archivesId", archivesId);
				map.put("type", type);
				int ls = archivesDao.queryForInt(hql, map);
				if (ls == 0) {
					newid.add(id);
				}
			}
			String types = "";
			String roleName = "";
			if (type == 0) {
				roleName = ROLE_DACX;
				types = "dept";
			} else if (type == 1) {
				roleName = ROLE_EJDAGLY;
				types = "user";
			} else {
				roleName = ROLE_DALRY;
				types = "user";
			}

			archivesDao.insert(newid, archivesId, type);
			newid.clear();

			String roleId = archivesDao.getRoleId(roleName);
			for (String id : ids) {
				int i = archivesDao.getRoleMemberCount(roleId, id, type);
				if (i == 0) {
					newid.add(id);
				}
			}
			roleMemberMaintain.insertRoleMember(newid, types, roleId);
			SecurityUtils.refreshComponentSecurityMetadata();
			SecurityUtils.refreshUrlSecurityMetadata();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * 通过archivesId与type获取ArchivesMember
	 * 
	 * @param page
	 * @param archivesId
	 * @param type
	 */
	@DataProvider
	public void getMemberIdByArchivesId(Page<ArchivesMember> page, Criteria criteria, String archivesId, int type) {
		archivesDao.getMemberIdByArchivesId(page, criteria, archivesId, type);
	}

	/**
	 * 根据memberId获取部门名称
	 * 
	 * @param memberId
	 * @return
	 */
	@DataProvider
	public String getDeptNameByMemberId(String memberId) {
		return deptService.loadDeptById(memberId).getName();
	}

	/**
	 * 根据memberId获取用户名称
	 * 
	 * @param memberId
	 * @return
	 */
	@DataProvider
	public String getUserNameByMemberId(String memberId) {
		return archivesDao.getCnameByMamberId(memberId);
	}

	/**
	 * 删除档案权限关系
	 * 
	 * @param id
	 * @param memberId
	 * @param type
	 */
	@Transactional
	@Expose
	public void deleteArchivesMemberById(String id, String memberId, int type) {
		try {
			String roleMemberId = archivesDao.getRoleMemberId(memberId, type);
			if (archivesDao.checkArchivesMemberByMemberId(memberId)) {
				roleMemberMaintain.deleteRoleMember(roleMemberId);
			}
			archivesDao.deleteArchivesMemberById(id);
			SecurityUtils.refreshComponentSecurityMetadata();
			SecurityUtils.refreshUrlSecurityMetadata();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * 删除树节点时，删除对应节点下的所有数据
	 * 
	 * @param archivesId
	 * @throws IOException
	 */
	@Transactional
	@Expose
	public void deleteArchivesSon(String archivesId) throws IOException {

		List<String> ls = archivesDao.getMamberIdByArchives(archivesId);
		for (String id : ls) {
			try {
				roleMemberMaintain.deleteRoleMember(id);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		archivesDao.deleteArchivesSon(archivesId);
		SecurityUtils.refreshComponentSecurityMetadata();
		SecurityUtils.refreshUrlSecurityMetadata();
	}

	@Transactional
	@Expose
	public void upload(List<String> num, String archivesId) throws Exception {
		String basePath = Configure.getString("ARCHIVE_FILE_UPLOAD_PATH");
		Path path = Paths.get(basePath);
		for (String string : num) {
			// 1，复制文件到新的文件夹里面
			File copyfiles = new File(PATHURL);
			File[] files = copyfiles.listFiles();
			for (int i = 0; i < files.length; i++) {
				if (files[i].getName().equals(string)) {
					path = path.resolve(UUID.randomUUID().toString());
					try (FileInputStream in = new FileInputStream(files[i])) {
						Files.copy(in, path);
					}
					// 2，删除原来文件夹里面的文件
					files[i].delete();
					// 3,维护表关系，保存数据
					archivesInputDao.saveArchivesContent(archivesId, files[i].getName(), path);
					path = Paths.get(basePath);
				}
			}
		}
	}
}
